<?php

namespace App\Store\Controllers\Financial\Statements;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Console\Commands\FinancialProfit;
use App\Http\Controllers\Controller;
use App\Store\Models\Financial\Statements\Voucher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 科目
 */
class VoucherController extends Controller
{


    /**
     * 新增凭证
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function dopostadd(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $validator = Validator::make($request->all(), [
            'voucher_number' => 'sometimes',
            'voucher_date' => 'required',
            'voucher_data.*' => 'required',
            'store_id' => 'required',
        ], [
            'voucher_date.required' => '日期不能为空',
            'voucher_data.*.required' => '凭证号必填',
            'store_id.required' => '门店必填'
        ]);

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $voucher_data = $params['voucher_data'] ?? [];
        $voucher_number = $params['voucher_number'] ?? '';


        $debit_amount = array_sum(array_column($voucher_data, 'debit_amount'));
        $credit_amount = array_sum(array_column($voucher_data, 'credit_amount'));

        if ($debit_amount == 0 || $credit_amount == 0) {
            return response()->json(['code' => '001', 'msg' => '借方金额或贷方金额为0']);
        }

        if (($debit_amount != $credit_amount)) {
            return response()->json(['code' => '001', 'msg' => '借方金额和贷方金额不相等']);
        }

        $year = date('Y', $params['voucher_date']);
        $month = date('m', $params['voucher_date']);
        if (empty($voucher_number)) {
            $voucher_number = (new Voucher())->getvoucherNumber($year, $month);
        }

        $inData = [];
        foreach ($voucher_data as $item) {
            $inData[] = [
                'cp_id' => $cp_id,
                'store_id' => $params['store_id'],
                'year' => $year,
                'month' => $month,
                'voucher_number' => $voucher_number,
                'serial_number' => $item['serial_number'],
                'debit_amount' => $item['debit_amount'] ?? 0,
                'credit_amount' => $item['credit_amount'] ?? 0,
                'voucher_date' => $params['voucher_date'] ?? strtotime(date('Y-m-d')),
                'abstract' => $item['abstract'] ?? '',
                'create_at' => time()

            ];
        }

        Voucher::query()->insert($inData);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    /**
     * 编辑
     */
    public function dopostedit(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $validator = Validator::make($request->all(), [
            'voucher_number' => 'required',
            'voucher_date' => 'required',
            'voucher_data.*' => 'required',
            'store_id' => 'required',
        ], [
            'voucher_number.required'=>'凭证号必填',
            'voucher_date.required' => '日期不能为空',
            'voucher_data.*.required' => '凭证数据不为空',
            'store_id.required' => '门店必填'
        ]);

        if ($validator->fails()) {
            $msg = $validator->errors()->first();
            return response()->json(['code' => '001', 'msg' => $msg]);
        }
        $params = $validator->validated();

        $voucher_data = $params['voucher_data'] ?? [];
        $debit_amount = array_sum(array_column($voucher_data, 'debit_amount'));
        $credit_amount = array_sum(array_column($voucher_data, 'credit_amount'));

        if ($debit_amount == 0 || $credit_amount == 0) {
            return response()->json(['code' => '001', 'msg' => '借方金额或贷方金额为0']);
        }

        if (($debit_amount != $credit_amount)) {
            return response()->json(['code' => '001', 'msg' => '借方金额和贷方金额不相等']);
        }

        $ids = array_column($voucher_data, 'id');
        $year = date('Y', $params['voucher_date']);
        $month = date('m', $params['voucher_date']);

        $count  = Voucher::query()
            ->where('voucher_number', $params['voucher_number'])
            ->where('cp_id', $cp_id)
            ->where('store_id', $params['store_id'])
            ->whereNotIn('id', $ids)
            ->where('is_del',1)
            ->count();

        if ($count>0) {
            return response()->json(['code' => '001', 'msg' => '凭证号已存在']);
        }
        $info  = Voucher::query()
            ->where('is_del',1)
            ->where('id', $ids[0])
            ->first();

        $before =$info->voucher_date;
        $voucher_date =$params['voucher_date']??0;

        foreach ($voucher_data as $item) {
            $id = $item['id'] ?? 0;
            $data = [
                'cp_id' => $cp_id,
                'store_id' => $params['store_id'],
                'year' => $year,
                'month' => $month,
                'voucher_number' => $params['voucher_number'],
                'serial_number' => $item['serial_number'],
                'debit_amount' => $item['debit_amount'] ?? 0,
                'credit_amount' => $item['credit_amount'] ?? 0,
                'voucher_date' => $voucher_date ?? strtotime(date('Y-m-d')),
                'abstract' => $item['abstract'] ?? '',
                'create_at' => time()

            ];

            Voucher::query()->where('id', $id)->update($data);

        }

        (new FinancialProfit())->executeProfit($before, $before+86399,$cp_id,$params['store_id']);
        (new FinancialProfit())->executeProfit($voucher_date, $voucher_date+86399,$cp_id,$params['store_id']);


        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 删除
     */
    public function dopostdel(Request $request)
    {
        $ids = $request->ids ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info = Voucher::query()
            ->whereIn('id', $ids)
            ->where('cp_id', $cp_id)
            ->first();
        if (empty($info)) {
            return response()->json(['code' => '001', 'msg' => '数据不存在']);
        }

        $voucher_date =$info->voucher_date;

        Voucher::query()
            ->whereIn('id', $ids)
            ->where('cp_id', $cp_id)
            ->update(['is_del' => 2, 'del_at' => time()]);

        (new FinancialProfit())->executeProfit($voucher_date, $voucher_date+86399,$cp_id,$info->store_id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function getinfo(Request $request)
    {
        $ids = $request->ids ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $list = Voucher::query()
            ->with(['storeinfo','subject'])
            ->whereIn('id', $ids)
            ->where('cp_id', $cp_id)
            ->where('is_del',1)
            ->get()
            ->toArray();

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }


    public function getlist(Request $request)
    {

        $list = (new Voucher())->getlist($request);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }


    public function export(Request $request)
    {

        $request->isgetall = 1;
        $list = (new Voucher())->getlist($request)['list'];

        $row = [
            ['table_header' => '记账凭证列表'],
            [
                'voucher_date' => '日期',
                'abstract' => '摘要',
                'voucher_number' => '凭证号',
                'store_name' => '门店',
                'subject_name' => '科目',
                'debit_amount' => '借方金额',
                'credit_amount' => '贷方金额',
            ]
        ];
        $exceldata = [];
        foreach ($list as $item) {
            $exceldata[] = [
                'voucher_date' => date('Y-m-d', $item['voucher_date']),
                'voucher_number' => (string)$item['voucher_number'],
                'subject_name' => $item['subject']['subject_name'] ?? '',
                'store_name' => $item['storeinfo']['store_name'] ?? '',
                'abstract' => $item['abstract'] ?? '',
                'debit_amount' => $item['debit_amount'] > 0 ? ($item['debit_amount'] / 100) : 0,
                'credit_amount' => $item['credit_amount'] > 0 ? ($item['credit_amount'] / 100) : 0
            ];

        }

        $filename = '记账凭证导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);

    }
}
